package com.jy.controller;


import com.jy.pojo.FileDetails;
import com.jy.pojo.vo.FileVo;
import com.jy.service.FileService;
import com.jy.utils.LayuiPage;
import com.jy.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.codec.binary.Base64;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

@RestController
public class FileController {
    @Autowired
    private FileService fileService;

    /**
     * 根据文件路径获取文件信息
     * @param fileVo：包含条件信息工具类
     * @return R：返回值（包含返回状态信息）
     */
    @GetMapping("/file")
    public R getList(FileVo fileVo){
        //List<FileDetails> list = fileService.getList(fileVo);
        List<FileDetails> list = fileService.getListByPath(fileVo);
        return R.succeed(list,"查询成功");
    }

    /**
     * 获取文件夹路径
     * @param fileVo：包含条件信息工具类
     * @return R：返回值（包含返回状态信息）
     */
    @GetMapping("/getDirs")
    public R getDirs(int id){
        Map<String, Object> dirs = fileService.getDirsByPath(id);
        return R.succeed(dirs, "查询成功");
    }

    /**
     * 多条件查询满足条件的文件并返回
     * @param fileVo
     * @return
     */
    @RequestMapping("/getFileDetails")
    public LayuiPage<FileDetails> getFileDetailsBySearch(FileVo fileVo){
        if(fileVo.isFlag()){
            List<FileDetails> fileDetailsBySearch = fileService.getFileDetailsBySearch(fileVo);
            int fileCountBySearch = fileService.getFileCountBySearch(fileVo);
            return new LayuiPage<FileDetails>(0,"",fileCountBySearch,fileDetailsBySearch);
        }else{
            return new LayuiPage<FileDetails>(1,"",0,null);
        }
    }

    /**
     * 多条件查询满足条件的文件并返回
     * @param fileVo
     * @return
     */
    @GetMapping("/getFileBySearch")
    public R getFileBySearch(@RequestParam(name = "fileText",required=true) String fileText,
                             @RequestParam(name = "isDir",required=true) int isDir){
        FileVo fileVo=new FileVo();
        fileVo.setExtendedFieldList(fileText);
        fileVo.setIsDir(isDir);
        List<FileDetails> fileDetailsBySearch = fileService.getFileDetailsBySearch(fileVo);
        return R.succeed(fileDetailsBySearch,"查询成功");
    }


    /**
     * 获取视频流
     * @param response
     * @param videoId 视频存放信息索引
     * @return
     * @author xWang
     * @Date 2020-05-20
     */
    @RequestMapping(value = "/getVideo/{path}/{name}",method = RequestMethod.GET)
    public void getVideo(HttpServletRequest request, HttpServletResponse response,@PathVariable("path") String path,@PathVariable("name") String fileName)
    {

        //视频资源存储信息
        //VideoSource videoSource = videoSourceService.selectById(videoId);
        response.reset();
        //获取从那个字节开始读取文件
        String rangeString = request.getHeader("Range");
        //String fileAddress="D:\\home\\Hamilton.mp4";
        String fileAddress=path;
        //String fileName="Hamilton.mp4";
        try {
            //获取响应的输出流
            OutputStream outputStream = response.getOutputStream();
            //File file = new File(videoSource.getFileAddress());
            File file=new File(fileAddress);
            if(file.exists()){
                RandomAccessFile targetFile = new RandomAccessFile(file, "r");
                long fileLength = targetFile.length();
                //播放
                if(rangeString != null){
                    long range = Long.valueOf(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
                    //设置内容类型
                    response.setHeader("Content-Type", "video/mp4");
                    //设置此次相应返回的数据长度
                    response.setHeader("Content-Length", String.valueOf(fileLength - range));
                    //设置此次相应返回的数据范围
                    response.setHeader("Content-Range", "bytes "+range+"-"+(fileLength-1)+"/"+fileLength);
                    //返回码需要为206，而不是200
                    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                    //设定文件读取开始位置（以字节为单位）
                    targetFile.seek(range);
                }else {//下载

                    //设置响应头，把文件名字设置好
                    response.setHeader("Content-Disposition", "attachment; filename="+fileName );
                    //设置文件长度
                    response.setHeader("Content-Length", String.valueOf(fileLength));
                    //解决编码问题
                    response.setHeader("Content-Type","application/octet-stream");
                }


                byte[] cache = new byte[1024 * 300];
                int flag;
                while ((flag = targetFile.read(cache))!=-1){
                    outputStream.write(cache, 0, flag);
                }
            }else {
                String message = "file:"+fileName+" not exists";
                //解决编码问题
                response.setHeader("Content-Type","application/json");
                outputStream.write(message.getBytes(StandardCharsets.UTF_8));
            }

            outputStream.flush();
            outputStream.close();

        } catch (FileNotFoundException e) {

        } catch (IOException e) {

        }
    }
}
